package org.example.greenhouse.service.impl;

import org.checkerframework.checker.units.qual.A;
import org.example.greenhouse.dao.UserDao;
import org.example.greenhouse.entity.Token;
import org.example.greenhouse.entity.User;
import org.example.greenhouse.result.Result;
import org.example.greenhouse.service.UserService;
import org.example.greenhouse.utils.JwtUtil;
import org.example.greenhouse.utils.LoginResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenServiceImpl tokenServiceImpl;

    public Result register(User user) {
        // 检查账号是否已存在
        if (userDao.findByAccount(user.getAccount()) != null) {
            return Result.error("账号已存在");
        }
        userDao.save(user);
        return Result.success("注册成功"); // 保存用户
    }

    public Result login(String account, String password) {
        User user = userDao.findByAccount(account);
        if (user == null || !user.getPassword().equals(password)) {
            return Result.error("账号或密码错误");
        }
        //登陆成功
        Map<String,Object> claims = new HashMap<>();
        claims.put("account",user.getAccount());
        claims.put("password",user.getPassword());
        String token2 = JwtUtil.genToken(claims);
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(token2);
        loginResponse.setData(user);

        // 登录成功后，获取 Token 并存储到数据库
        Token token = tokenServiceImpl.fetchTokenFromUrl();
        tokenServiceImpl.saveToken(token);

        return Result.success(loginResponse,"登陆成功"); // 返回登录成功的用户
    }



}
